package com.shengchang.hu.supervision;


import android.Manifest;
import android.app.DownloadManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;

import android.content.DialogInterface;
import android.content.Intent;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;


import com.chiclam.android.updater.Updater;
import com.chiclam.android.updater.UpdaterConfig;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.shengchang.hu.supervision.Adapter.GridViewAdapter;
import com.shengchang.hu.supervision.Adapter.SimpleArrayAdapter;
import com.shengchang.hu.supervision.Application.App;

import com.shengchang.hu.supervision.UI.BaseActivity;

import com.shengchang.hu.supervision.UI.BloodBagKeshiActivity;
import com.shengchang.hu.supervision.UI.CheckedActivity;

import com.shengchang.hu.supervision.UI.DeviceListActivity;
import com.shengchang.hu.supervision.UI.LoginActivity;

import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener {


    Spinner spinner;

    RollPagerView viewPager;

    GridView gridview;
    public   String str;
    private Button blesearch;
    private long mPressedBackTime;
    private SimpleArrayAdapter arrAdapter;
   private SharedPreferences settings;
   private SharedPreferences.Editor editorsettings;
    private SharedPreferences Blesettings;
    private SharedPreferences.Editor Bleeditorsettings;
    private String style;
    private String styleCode;
    /* 新版本的下载地址*/
    public  String url;
    private String mApkFileUrl ;
    public String versinName;
    public int versionCode;
    String BluetoothAddress;
    Handler mHandler;
    Boolean b_scaleIsConnect=Boolean.FALSE;
    final Boolean SendMoudle=true;
    private BluetoothAdapter mBluetoothAdapter=null;
    public   int[] icon={R.drawable.shouji,R.drawable.ruku,R.drawable.chuku,R.drawable.bulou

    };
    private  static  final  String  UPDATA_API=Contants.Updata_API;
    OkHttpClient mOkhttp=new OkHttpClient();
    private  static  final String RUNING_URL=Contants.RUN_API;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                        @Override
                        public void run() {

                            OpenBlue();
                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }


            }
        }).start();

    }

    private void OpenBlue() {
        //        ButterKnife.bind(this);

        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mHandler=new Handler()
        {
            public void handleMessage(Message msg)
            {
                switch(msg.what)
                {
                    case 2:
                        if(msg.arg1<2) {

                            b_scaleIsConnect=Boolean.FALSE;
                        }
                        else {
                            b_scaleIsConnect = Boolean.TRUE;
                            if(SendMoudle)
                            {

                            }
                        }
                        break;

                }
            }
        };
        mBluetoothAdapter.enable();
        permission();
        if (checkStartType(getIntent())) {
            return;
        }
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initView() {
        spinner=findViewById(R.id.spnkesh);
        spinnergetdata();
        blesearch=findViewById(R.id.blesearch);
        blesearch.setOnClickListener(this);
        settings = getSharedPreferences("preferences_settings",Context.MODE_PRIVATE);
        editorsettings = settings.edit();
        Blesettings=getSharedPreferences("preferences_blesettings",Context.MODE_PRIVATE);
        Bleeditorsettings=Blesettings.edit();
        viewPager=findViewById(R.id.view_pager);
        gridview=findViewById(R.id.gridview);
        viewPager.setAdapter(new ImageNormalAdapter());
        viewPager.setHintView(null);
        gridview.setAdapter(new GridViewAdapter(this));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (icon[position]){
                    case R.drawable.shouji:

                        Intent intent = new Intent(MainActivity.this,CheckedActivity.class);
                        intent.putExtra("maccode", styleCode);
                        startActivity(intent);

                        break;
                    case R.drawable.ruku:

                        //一键入库
//                        showProgressDialog();
//                        runinRequest();
                        startActivity(new Intent(MainActivity.this,BloodBagKeshiActivity.class));
                        //暂存处刷卡功能
//                        startActivity(new Intent(MainActivity.this,TemporaryStorageActivity.class));
                        break;
                    case R.drawable.chuku:
                        //退出登录
                        MainActivity.startActivity(MainActivity.this, MainActivity.StartType.LOGOUT);
                        MainActivity.this.finish();
                        //院内收集
//                startActivity(new Intent(MainActivity.this,ExtramuralActivity.class));
                break;
                case R.drawable.bulou:
                    request();
//                    showShortToast("请在暂存处设备上操作");
////                startActivity(new Intent(MainActivity.this,CheckOutActivity.class));
                break;
            }
            }
        });


        }


    private void request() {
        RequestBody formBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(UPDATA_API)
                .post(formBody)
                .build();
        Log.d("sdeujciadrrc", UPDATA_API );
        Call call = mOkhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("请求失败，请确认网络");
                                // 放在UI线程弹Toast

                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String loginstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoginResPonse(loginstr);
                    }
                });

            }
        });

    }

    private void LoginResPonse(String loginstr) {
        try {
            JSONObject jsonObject = new JSONObject(loginstr);
            String code = jsonObject.getString("message");
            if (code.equals("2000")){

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject objectdata = new JSONObject(loginstr);
            url=objectdata.getString("path");
            mApkFileUrl=Contants.UPDATA_URL+url;
            Log.d("hdheusakw", mApkFileUrl);
            Double  code=objectdata.getDouble("version");
            if (Double.parseDouble(versinName)< code){

//                   Toast.makeText(getActivity(),"等待版本更新",Toast.LENGTH_SHORT).show();
                showdialog();
            }else  if (Double.parseDouble(versinName)>=code){
                showShortToast("已经是最新版本");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public  void showdialog() {
        new AlertDialog.Builder(this)
                .setTitle("有新版本啦!")
                .setMessage("1.增加版本更新功能" +"\n"+
                        "2.修改卡片不符提示"+"\n")
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        download(mApkFileUrl);
//                        Intent i=new Intent(getActivity(),UpLoadActivity.class);
//                        i.putExtra("url",url);
//                        startActivity(i);

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    public void download(String  url) {
        UpdaterConfig config = new UpdaterConfig.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setDescription(getString(R.string.system_download_description))
                .setFileUrl(url)
                .setCanMediaScanner(true)
                .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                        | DownloadManager.Request.NETWORK_WIFI)

                .build();
        Updater.get().showLog(true).download(config);
    }
    /*
     * 得到本地的versioncode*/
    public void getVersionNameCode(){
        PackageManager pm=this.getPackageManager();
        try {
            PackageInfo info=pm.getPackageInfo(this.getPackageName(),0);
            versinName=info.versionName;
            versionCode=info.versionCode;
            Log.d("irowkd", String.valueOf(versinName));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        getVersionNameCode();
    }

    private void spinnergetdata() {
        final SharedPreferences blesettings = getSharedPreferences("preferences_blesettings",0);
        //数据
        List<String> data_list = new ArrayList<String>();
        data_list.add("请选择");
        data_list.add("1号车");
        data_list.add("2号车");
        data_list.add("3号车");
        data_list.add("4号车");
        data_list.add("5号车");
        data_list.add("6号车");

        //适配器
        arrAdapter = new SimpleArrayAdapter<String>(this, R.layout.simple_spinner_item, data_list);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.layout_spinner_item);
        //加载适配器
        spinner.setAdapter(arrAdapter);
        spinner.setSelection(data_list.size() - 1, true);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                style = spinner.getSelectedItem().toString();
                style =  adapterView.getItemAtPosition(i).toString();
                Log.d("hesf", style);
                editorsettings.putInt("SelectedPosition", i);
                editorsettings.putString("SelectedName", style);
                editorsettings.commit();
                if (settings.getString("SelectedName", "").equals("1号车")) {
                    if (blesettings.getString("BluetoothAddress","").equals("")){

                        styleCode = "00:15:83:F0:EF:98";

                    }else{

                        styleCode=blesettings.getString("BluetoothAddress","");
                    }
                    showShortToast(styleCode);
                } else if ( settings.getString("SelectedName", "").equals("2号车")) {
                    if (blesettings.getString("BluetoothAddress","").equals("")){
                        styleCode = "00:15:83:F0:EF:FB";

                    }else{
                        styleCode=blesettings.getString("BluetoothAddress","");
                    }
                    showShortToast(styleCode);

                } else if ( settings.getString("SelectedName", "").equals("3号车")) {
                    if (blesettings.getString("BluetoothAddress","").equals("")){
                        styleCode = "00:15:83:F0:EF:98";

                    }else{
                        styleCode=blesettings.getString("BluetoothAddress","");
                    }
                    showShortToast(styleCode);

                } else if ( settings.getString("SelectedName", "").equals("4号车")) {
                    if (blesettings.getString("BluetoothAddress","").equals("")){
                        styleCode = "00:15:83:F0:EF:98";
                    }else{
                        styleCode=blesettings.getString("BluetoothAddress","");

                    }
                    showShortToast(styleCode);


                } else if ( settings.getString("SelectedName", "").equals("5号车")) {
                    if (blesettings.getString("BluetoothAddress","").equals("")){
                        styleCode = "00:15:83:F0:EF:98";

                    }else{
                        styleCode=blesettings.getString("BluetoothAddress","");
                    }
                    showShortToast(styleCode);

                }
                   if (styleCode!=null){
                       Log.d("uiewq", styleCode);
                   }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        SharedPreferences settings = getSharedPreferences("preferences_settings",0);
        int position = settings.getInt("SelectedPosition", 0 );

        spinner.setSelection(position);
    }

    private void runinRequest() {

        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())

                .build();
        Request request = new Request.Builder()
                .url(RUNING_URL)
                .post(formBody)
                .build();
        Log.d("sdeujcia",RUNING_URL+"?id="+App.getApp().getToken());
        Call newCall = mOkhttp.newCall(request);
        newCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {						//
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        parses(str);

                    }
                });
            }
        });

    }

    private void parses(String str) {

        try {
            JSONObject mJson=new JSONObject(str);
            String mesgJson=mJson.getString("message");
            if (mesgJson.equals("20004")){
                dismissProgressDialog();
                showShortToast("请求异常");
            }else if (mesgJson.equals("20005")){
                dismissProgressDialog();
                showShortToast("入库成功");
            }else if (mesgJson.equals("20007")){
                dismissProgressDialog();
                showShortToast("没有入库的医废");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    private void permission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("蓝牙授权");
                builder.setMessage("点击确定对蓝牙授权");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                        }
                    }
                });
                builder.show();
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.blesearch:
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(mIntent, 0);
                }
                else {
                    Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(serverIntent, 1);
                }

                break;

        }
    }

    class ImageNormalAdapter extends StaticPagerAdapter {
        int[] imgs = new int[]{
                R.mipmap.form2,

        };

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(container.getContext());
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setImageResource(imgs[position]);
            return view;
        }


        @Override
        public int getCount() {
            return imgs.length;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 0:
                if (resultCode == RESULT_OK)
                {
                    Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(serverIntent, 1);
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    //String name=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
                    BluetoothAddress= data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    Log.d("iueijmx", String.valueOf(BluetoothAddress));
                    showShortToast("绑定成功");
                    if (BluetoothAddress.length()>0){
                        Bleeditorsettings.putString("BluetoothAddress",BluetoothAddress);
                        Bleeditorsettings.commit();

                        }else {
                        showShortToast("未找到蓝牙设备");
                    }

                    }
                break;
        }
    }
    @Override
    protected void onNewIntent(Intent paramIntent)
    {
        super.onNewIntent(paramIntent);
        checkStartType(paramIntent);
    }

    public static void startActivity(Context paramContext, StartType paramStartType)
    {
        Intent localIntent = new Intent(paramContext, MainActivity.class);
        localIntent.putExtra("type", paramStartType.getType());
        paramContext.startActivity(localIntent);
    }

    private boolean checkStartType(Intent paramIntent)
    {
        boolean bool = false;
        if (paramIntent.getIntExtra("type", 0) == StartType.LOGOUT.getType())
        {
            App.getApp().setToken(null);
            LoginActivity.startActivity(this);
            finish();
            bool = true;
        }
        return bool;
    }

    public static enum StartType
    {
        LOGOUT(10);

        private int mType;

        private StartType(int paramInt)
        {
            this.mType = paramInt;
        }

        public int getType()
        {
            return this.mType;
        }
    }

    @Override
    public void onBackPressed() {
        long l = System.currentTimeMillis();
        if (l - this.mPressedBackTime > 3000L) {
            showLongToast("再次轻触返回键退出程序");
            this.mPressedBackTime = l;
            return;
        }
        finish();
    }
}
